<template>
  <view class="container">
    <view class="header-wrapper">
      <view class="header-title">首页</view>
      <!-- Header -->
      <view class="header">
        <view class="diamond-member">
          <image :src="images.icons.diamond" class="diamond-icon"></image>
          <text>钻石会员</text>
        </view>
        <text class="greeting">{{ getUserTitle() }}, {{ getGreeting() }}</text>
      </view>

      <!-- Banner -->
      <swiper class="banner" circular autoplay interval="3000" duration="500" indicator-dots
        indicator-color="rgba(255, 255, 255, 0.3)" indicator-active-color="#FFFFFF">
        <swiper-item class="banner-item-box" v-for="i in 3" :key="i">
          <view class="banner-item">
            <image :src="images.banner.medical" mode="aspectFill"></image>
          </view>
        </swiper-item>
      </swiper>

      <!-- Check-in Center -->
      <view class="check-in-box">
        <image src="https://img.qffssd.com/novel/img/cosmetic/daka-center.png" class="check-title"></image>
        <text class="check-subtitle">打卡好礼享不停</text>
        <text class="check-btn" @tap="handleCheckIn">立即打卡</text>
      </view>
    </view>

    <!-- AI Assistant Section -->
    <view class="ai-section">
      <!-- 左侧机器人区域 -->
      <view class="ai-card" @tap="handleAiAssistant">
        <image :src="images.icons.robot" mode="aspectFit" class="robot-img"></image>
        <text class="ai-title">智能皮肤助手</text>
      </view>

      <!-- 右侧信息区域 -->
      <view class="info-card">
        <view class="skin-index" @tap="handleSkinAi">
          <image :src="images.icons.aiAssistant" mode="aspectFit" class="ai-assistant"></image>
          <view class="index-left">AI拍照测肤
            <text class="index-title"></text>
          </view>
        </view>

        <!-- 修改按钮区域为垂直排列 -->
        <view class="action-buttons">
          <view class="action-btn btn-2" @tap="handleSkinReport">
            <view class="action-text">您的肤龄</view>
            <view class="score-wrapper">
              <canvas type="2d" id="progressCanvas" class="progress-canvas"></canvas>
              <view class="score-box">
                <view class="score">{{ score }}</view>
                <!-- <view class="unit">分</view> -->
              </view>
            </view>
            <view class="solution-btn">点击查看解决方案></view>
          </view>
          <view class="action-btn" @tap="handleNearbyStore(1)">
            <image :src="images.icons.calendar" mode="aspectFit" class="action-icon"></image>
            <text class="action-text">预约管理</text>
          </view>
        </view>
      </view>
    </view>

    <!-- Hot Recommend -->
    <view class="recommend-section">
      <view class="section-title">活动推荐
        <view class="title-bg"></view>
      </view>
      <view class="category-tabs">
        <text class="tab" :class="{ active: activeTypeIndex === index }" v-for="(type, index) in goodsTypes"
          :key="index" @tap="handleTypeChange(index)">{{
            type.typeName
          }}</text>
      </view>

      <view class="product-grid">
        <view class="product-item" v-for="(item, index) in goodsList" :key="index" @tap="handleGoodsDetail(item)">
          <image :src="BASE_URL + item.headerImg" mode="aspectFill"></image>
          <view class="product-name">
            <view class="product-name-text">{{ item.name }}</view>
            <view class="product-desc">{{ item.description }}</view>
          </view>

        </view>
      </view>

      <view class="loading-more">
        <text v-if="isLoading">加载中...</text>
        <text v-else-if="!hasMore">没有更多了</text>
        <text v-else>上拉加载更多</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onReachBottom } from '@dcloudio/uni-app';
import { images } from '@/config/images';
import { useUserStore } from '@/stores/user';
import { getGoodsTypeList, getGoodsList } from '@/api/goods';
import type { GoodsType, GoodsInfo } from '@/api/goods';
import { BASE_URL, IMG_URL } from '@/utils/request';
const userStore = useUserStore();

const score = ref(0);
const targetScore = ref(90);
const activeTypeIndex = ref(0);
const goodsTypes = ref<GoodsType[]>([]);
const goodsList = ref<GoodsInfo[]>([]);

// 分页相关状态
const pageNum = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const isLoading = ref(false);

// 获取商品类型列表
const fetchGoodsTypes = async () => {
  return await fetchGoodsList();
  try {
    const types = await getGoodsTypeList();
    goodsTypes.value = types.rows;
    console.log('商品类型列表：', types);
    // 获取第一个类型的商品列表
    if (types.rows.length > 0) {
      await fetchGoodsList(types.rows[0].id);
    }
  } catch (error) {
    console.error('获取商品类型失败：', error);
    uni.showToast({
      title: '获取商品类型失败',
      icon: 'none',
    });
  }
};

// 获取商品列表
const fetchGoodsList = async (typeId?: number, isLoadMore = false) => {
  if (isLoading.value || (!isLoadMore && !hasMore.value)) return;

  try {
    isLoading.value = true;
    const res = await getGoodsList({
      status: '0',
      noticeType: '3',
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });

    if (isLoadMore) {
      goodsList.value = [...goodsList.value, ...res.rows];
    } else {
      goodsList.value = res.rows;
    }

    // 判断是否还有更多数据
    hasMore.value = res.rows.length === pageSize.value;
    if (hasMore.value) {
      pageNum.value++;
    }
  } catch (error) {
    console.error('获取商品列表失败：', error);
    uni.showToast({
      title: '获取商品列表失败',
      icon: 'none',
    });
  } finally {
    isLoading.value = false;
  }
};

// 切换商品类型
const handleTypeChange = async (index: number) => {
  activeTypeIndex.value = index;
  const typeId = goodsTypes.value[index].id;
  // 重置分页状态
  pageNum.value = 1;
  hasMore.value = true;
  await fetchGoodsList(typeId);
};

// 监听页面滚动到底部
uni.$on('onReachBottom', () => {
  if (hasMore.value && !isLoading.value && goodsTypes.value.length > 0) {
    const currentTypeId = goodsTypes.value[activeTypeIndex.value].id;
    fetchGoodsList(currentTypeId, true);
  }
});



// 获取问候语
const getGreeting = () => {
  const hour = new Date().getHours();
  if (hour < 6) return '凌晨好';
  if (hour < 9) return '早上好';
  if (hour < 12) return '上午好';
  if (hour < 14) return '中午好';
  if (hour < 17) return '下午好';
  if (hour < 19) return '傍晚好';
  return '晚上好';
};

// 计算用户称呼
const getUserTitle = () => {
  if (!userStore.userInfo) return '游客';
  const name = userStore.userInfo.nickName;
  return name ? `${name}` : '游客';
};

const drawProgress = (ctx: any, percentage: number) => {
  const width = 60;
  const height = 60;
  const lineWidth = 6;
  const radius = (width - lineWidth) / 2;
  const centerX = width / 2;
  const centerY = height / 2;

  // 清除画布
  ctx.clearRect(0, 0, width, height);

  // 绘制背景圆环
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
  ctx.lineWidth = lineWidth;
  ctx.strokeStyle = '#a17bf7';
  ctx.stroke();

  // 创建渐变，使用指定的颜色
  const gradient = ctx.createLinearGradient(0, 0, width, 0);
  // gradient.addColorStop(0, '#F9568F');
  gradient.addColorStop(0.25, '#FFD0AA');
  gradient.addColorStop(0.5, '#93ECFA');
  // gradient.addColorStop(0.75, '#FFD0AA');
  gradient.addColorStop(1, '#7E77F9');

  // 绘制进度圆环
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + 2 * Math.PI * percentage);
  ctx.lineWidth = lineWidth;
  ctx.strokeStyle = gradient;
  ctx.stroke();
};

let timer: number;
onMounted(() => {
  fetchGoodsTypes();
  initCanvas();
});

// 初始化 canvas
const initCanvas = () => {
  const query = uni.createSelectorQuery();
  query
    .select('#progressCanvas')
    .fields({ node: true, size: true })
    .exec((res) => {
      const canvas = res[0].node;
      const ctx = canvas.getContext('2d');

      // 设置canvas尺寸
      const dpr = uni.getSystemInfoSync().pixelRatio;
      canvas.width = 60 * dpr;
      canvas.height = 60 * dpr;
      ctx.scale(dpr, dpr);

      // 启动动画
      timer = setInterval(() => {
        if (score.value < targetScore.value) {
          score.value++;
          drawProgress(ctx, score.value / 100);
        } else {
          clearInterval(timer);
        }
      }, 20);
    });
};

// 跳转到附近门店页面
const handleNearbyStore = (type: number) => {
  uni.navigateTo({
    url: '/pages/store/nearby?type=' + type,
  });
};

// 跳转到智能皮肤助手页面
const handleAiAssistant = () => {
  uni.navigateTo({
    // url: '/pages/ai/skin',
    url: '/pages/ai/demo',
  });
};

// 跳转到每日打卡列表
const handleCheckIn = () => {
  uni.switchTab({
    url: '/pages/task/index',
    fail: (err) => {
      console.error('跳转失败：', err);
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      });
    }
  });
};

// 跳转到测肤报告
const handleSkinReport = () => {
  uni.navigateTo({
    url: '/pages/mall/detail-card'
  });
};

// 跳转到商品详情页面
const handleGoodsDetail = (item: any) => {
  uni.navigateTo({
    url: `/pages/mall/detail?id=${item.id}`,
    fail: (err) => {
      console.error('跳转失败：', err);
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      });
    }
  });
};

const handleSkinAi = () => {
  uni.navigateTo({
    url: '/pages/skin-ai/index'
  });
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.score-wrapper {
  position: relative;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  .progress-canvas {
    width: 60rpx;
    height: 60rpx;
  }

  .score-box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    background: transparent;


    .score {
      font-size: 20rpx;
      font-weight: bold;
      color: #fff;
    }

    .unit {
      font-size: 16rpx;
      color: #fff;
      margin-top: 8rpx;
    }
  }
}

.header-wrapper {
  width: 100%;
  height: 714rpx;
  background: url(https://img.qffssd.com/novel/img/cosmetic/home-top-bg.webp) no-repeat center center;
  background-size: 100% 100%;

  .header-title {
    margin-top: 100rpx;
    text-align: center;
    color: #ffffff;
    font-weight: bold;
    font-size: 36rpx;
  }
}

.header {
  margin-top: 49rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46rpx;

  .diamond-member {
    background-color: #1f1340;
    border-top-right-radius: 23rpx;
    border-bottom-right-radius: 23rpx;
    padding: 4rpx 20rpx;
    display: flex;
    align-items: center;
    gap: 10rpx;

    .diamond-icon {
      width: 35rpx;
      height: 35rpx;
      margin-right: 14rpx;
    }

    text {
      color: #ffffff;
      font-size: 34rpx;
    }
  }

  .greeting {
    color: #ffffff;
    font-size: 34rpx;
    padding-right: 20rpx;
  }
}

.banner {
  width: 700rpx;
  height: 320rpx;
  margin: 0 auto;
  border-radius: 24rpx;
  overflow: hidden;
  margin-top: 23rpx;

  .banner-item-box {
    border-radius: 24rpx;
  }

  .banner-item {
    width: 100%;
    height: 100%;
    border-radius: 24rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    image {
      width: 100%;
      height: 100%;
      border-radius: 24rpx;
    }
  }
}

.check-in-box {
  margin: 40rpx auto 0;
  width: 704rpx;
  height: 80rpx;
  background: url(https://img.qffssd.com/novel/img/cosmetic/daka.webp) no-repeat center center;
  background-size: 100% 100%;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  box-sizing: border-box;
  padding: 0 20rpx;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  overflow: hidden;

  .check-title {
    width: 140rpx;
    height: 28rpx;
    padding-right: 15rpx;
  }

  .check-subtitle {
    border-left: 2px solid #fdf4d9;
    padding-left: 15rpx;
    font-family: Source Han Sans CN;
    font-size: 27rpx;
    color: #fdf4d9;
  }

  .check-btn {
    margin-left: 164rpx;
    width: 139rpx;
    height: 46rpx;
    background: linear-gradient(90deg, #e9cba0, #fff9df);
    border-radius: 22rpx;
    font-weight: bold;
    font-size: 24rpx;
    color: #935d0c;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.ai-section {
  margin: 20rpx;
  display: flex;
  gap: 20rpx;
}

.ai-card {
  width: 280rpx;
  height: 320rpx;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(-21deg, #e4dfff, #fefefe);
  border-radius: 19rpx;

  .robot-img {
    width: 130rpx;
    height: 206rpx;
    margin-bottom: 40rpx;
    font-size: 28rpx;
    color: #212121;
  }

  .ai-title {
    font-size: 28rpx;
    color: #333;
  }
}

.info-card {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.skin-index {
  width: 422rpx;
  height: 175rpx;
  box-sizing: border-box;
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0rpx 6rpx 50rpx 1rpx rgba(67, 87, 234, 0.14);
  border-radius: 19rpx;
  background: linear-gradient(-85deg, #0790f566, #a17bf7d1);
  color: #fff;
  font-size: 40rpx;

  .ai-assistant {
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
  }
}

.action-buttons {
  display: flex;
  flex-direction: row;
  gap: 14rpx;

  .action-btn {
    width: 206rpx;
    height: 120rpx;
    background: linear-gradient(138deg, #6f3ded, #a17bf7);
    border-radius: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
    position: relative;

    .action-icon {
      width: 42rpx;
      height: 40rpx;
    }

    .i-2 {
      width: 34rpx;
      height: 40rpx;
    }

    .action-text {
      font-size: 28rpx;
      color: #ffffff;
    }
  }

  .btn-2 {
    flex-direction: row;
    background: linear-gradient(138deg, #3b56ed, #7394f2);
    align-items: flex-start;

    .solution-btn {
      font-size: 18rpx;
      width: 100%;
      color: #ffffff;
      position: absolute;
      bottom: 18rpx;
      left: 8rpx;
    }

    .action-text {
      margin-top: 28rpx;
    }

    .score-wrapper {
      margin-top: 18rpx;
    }
  }
}

.recommend-section {
  padding: 20rpx;
  background: #f5f7ff;

  .section-title {
    font-weight: bold;
    font-size: 34rpx;
    color: #222222;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    margin-bottom: 40rpx;

    .title-bg {
      width: 124rpx;
      height: 12rpx;
      background: linear-gradient(138deg, #724eff, #a48ff6);
      opacity: 0.5;
      position: absolute;
      left: 50%;
      bottom: -4rpx;
      transform: translate(-50%, -50%);
    }
  }

  .category-tabs {
    position: relative;
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    margin: 20rpx 0;
    overflow-x: auto;
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;

    &::-webkit-scrollbar {
      display: none;
    }

    .tab {
      position: relative;
      padding: 10rpx 30rpx;
      margin: 0 10rpx;
      color: #666;
      font-size: 28rpx;
      background: #f5f5f5;
      border-radius: 28rpx;
      transition: all 0.3s;

      &.active {
        color: #fff;
        background: #8c5cdd;
      }

      &:first-child {
        margin-left: 32rpx;
      }

      &:last-child {
        margin-right: 32rpx;
      }
    }

  }

  .product-grid {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
    gap: 20rpx;
    margin-bottom: 20rpx;

    .product-item {
      width: 706rpx;
      height: 455rpx;
      border-radius: 20rpx;
      margin-bottom: 20rpx;
      box-sizing: border-box;
      overflow: hidden;
      position: relative;

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .product-name {
        position: absolute;
        bottom: 0;
        left: 0;
        height: 110rpx;
        width: 100%;
        font-size: 32rpx;
        color: #222222;
        padding: 20rpx;
        box-sizing: border-box;
        background: #FFFFFF;
        opacity: 0.7;


        .product-name-text {
          width: 100%;
          font-weight: bold;
          font-size: 32rpx;
          color: #222222;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        .product-desc {
          width: 100%;
          font-size: 28rpx;
          color: #333333;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }




      .product-info {
        position: absolute;
        right: 14rpx;
        top: 27rpx;
        width: 112rpx;
        height: 43rpx;
        overflow: hidden;
        background: linear-gradient(138deg, #3b56ed, #7394f2);
        box-shadow: 0rpx 6rpx 50rpx 1rpx rgba(67, 87, 234, 0.44);
        border-radius: 22rpx 0rpx 0rpx 22rpx;
        font-size: 26rpx;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .loading-more {
    text-align: center;
    padding: 20rpx 0;
    color: #999;
    font-size: 24rpx;
  }
}
</style>
